package com.forlove.app.qselect.index.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseFragment;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.common.widget.GuideWindow;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.common.widget.recyview.EndLessOnScrollListener;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.qselect.MainTabView;
import com.forlove.app.qselect.answer.ui.AnswerSubjectActivity;
import com.forlove.app.qselect.index.adapter.MineCircleAdapter;
import com.forlove.app.qselect.index.entity.FriendCircleInfoEntity;
import com.forlove.app.qselect.index.entity.PageEntity;
import com.forlove.app.qselect.index.presenter.MineCircleInfoPresenter;
import com.forlove.app.qselect.index.view.MineCircleInfoView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 首页我的魅力fragment
 * Created by yjl on 2017/10/11.
 */

public class MineCircleInfoFragment extends BaseFragment implements MineCircleInfoView, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.view_mine_info_refresh)
    SwipeRefreshLayout view_mine_info_refresh;

    @BindView(R.id.recycler_mine_info)
    RecyclerView recycler_mine_info;

    private MineCircleAdapter friendCircleAdapter;
    private List<FriendCircleInfoEntity> friendCircleEntities = new ArrayList<>();
    private MineCircleInfoPresenter mineCircleInfoPresenter;
    private boolean isloadingMore = false;//是否正在加载更多
    private boolean isRefresh = false;
    private Handler mHandler;
    private static List<MainTabView.ActiveFlagListener> activeFlagListeners = new ArrayList<>();
    public static int unReadNum = 0;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine_circle_info;
    }

    public static void setActiveFlagListener(MainTabView.ActiveFlagListener activeFlagListener) {
        if (activeFlagListener != null) {
            activeFlagListeners.add(activeFlagListener);
        }
    }

    @Override
    public void onSelected(int pos) {
        if (IndexFragment.getPos() == IndexFragment.POSITION_INDEX_MiNE) {
            LogUtil.e("yjl", "onSelected MineCircleInfoFragment");
            if (getView() == null && getActivity() != null) {
                mContext = getActivity();
                initFragmentView();
            } else if (!isInit && getView() != null) {
                mContext = getActivity();
                initFragmentView();
            } else if (isInit && getView() != null) {
                if (MineCircleInfoFragment.unReadNum > 0) {
                    requestFriendCircleInfo();
                }
            }
        }
    }

    @Override
    protected void initFragmentView() {
        if (!isInit && IndexFragment.getPos() == IndexFragment.POSITION_INDEX_MiNE) {
            initFragment();
            isInit = true;
        }
    }

    private void showGuideView(View mainView) {
        if (mContext == null) {
            return;
        }
        boolean ishow = FriendManager.showMineGuideView(mContext);
        if (ishow) {
            LinearLayout linearLayout = (LinearLayout) mContext.getLayoutInflater().
                    inflate(R.layout.layout_show_mine_guide, null);
            Display display = mContext.getWindowManager().getDefaultDisplay();
            linearLayout.setLayoutParams(new ViewGroup.LayoutParams(display.getWidth(), display.getHeight()));
            GuideWindow.Builder builder = new GuideWindow.Builder(getActivity());
            builder.setContentView(linearLayout);
            builder.showAtLocation(mainView, Gravity.CENTER, 0, 0);
            FriendManager.saveMindeGuideView(mContext, false);
        }
    }

    private void initCacheData() {
        HandlerThread handlerThread = new HandlerThread("cacheMineCircle");
        handlerThread.start();
        Handler handler = new Handler(handlerThread.getLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    String infoString = DataManager.getMineCircleCache(getContext());
                    if (!TextUtils.isEmpty(infoString)) {
                        List<FriendCircleInfoEntity> circleInfoEntities =
                                ParseHelper.getModelList(infoString, "data.list", FriendCircleInfoEntity.class);
                        if (circleInfoEntities != null
                                && friendCircleEntities.size() == 0) {
                            friendCircleEntities.clear();
                            friendCircleEntities.addAll(circleInfoEntities);
                            Handler cacheHandler = new Handler(getContext().getMainLooper(), new Handler.Callback() {
                                @Override
                                public boolean handleMessage(Message msg) {
                                    switch (msg.what) {
                                        case 40001:
                                            friendCircleAdapter.updateDatas(friendCircleEntities);
                                            break;
                                    }
                                    return false;
                                }
                            });
                            cacheHandler.sendEmptyMessage(40001);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }


    private void initFragment() {
//        showGuideView(view_mine_info_refresh);
        if (mineCircleInfoPresenter == null) {
            mineCircleInfoPresenter = new MineCircleInfoPresenter(this);
        }
        if (mHandler == null) {
            mHandler = new Handler();
        }
        if (view_mine_info_refresh != null) {
            view_mine_info_refresh.setOnRefreshListener(this);
            view_mine_info_refresh.setColorSchemeResources(R.color.common_green);
        }
        initCacheData();
        friendCircleAdapter = new MineCircleAdapter(mContext, R.layout.item_mine_charm,
                friendCircleEntities, mineCircleInfoPresenter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recycler_mine_info.setLayoutManager(linearLayoutManager);
        recycler_mine_info.setAdapter(friendCircleAdapter);
        friendCircleAdapter.updateDatas(friendCircleEntities);
        recycler_mine_info.addOnScrollListener(new EndLessOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                if (!isloadingMore) {
                    isloadingMore = true;
                    friendCircleAdapter.showFootLoading();
                    mineCircleInfoPresenter.loadMoreFriendInfData();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            friendCircleAdapter.hideFooterView();
                            isloadingMore = false;
                        }
                    }, 6000);
                }
            }
        });

        friendCircleAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, AnswerSubjectActivity.class);
                Bundle bundle = new Bundle();
                LogUtil.e("yjl", "position:" + position);
                FriendCircleInfoEntity friendCircleInfoEntity = friendCircleEntities.get(position);
                if (friendCircleInfoEntity.isread == 0) {
                    friendCircleInfoEntity.isread = 1;
                    friendCircleAdapter.notifyItemChanged(position);
                    if (unReadNum > 0) {
                        unReadNum--;
                        for (MainTabView.ActiveFlagListener activeFlagListener : activeFlagListeners) {
                            activeFlagListener.readMineCircle(unReadNum);
                        }
                    }
                }

                bundle.putSerializable("friendCircleInfoEntity", friendCircleInfoEntity);
                bundle.putInt("type", 2); //魅力值是2
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        requestFriendCircleInfo();
    }

    @Override
    public void onRefresh() {
        //刷新
        if (!isRefresh) {
            requestFriendCircleInfo();
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isRefresh && view_mine_info_refresh.isRefreshing()) {
                    view_mine_info_refresh.setRefreshing(false);
                }
            }
        }, 6000);
    }

    private void requestFriendCircleInfo() {
        PageEntity pageEntity = new PageEntity();
        pageEntity.mPage = 1;
        pageEntity.mType = 2;
        if (mineCircleInfoPresenter != null) {
            isRefresh = true;
            mineCircleInfoPresenter.loadFriendInfoData(pageEntity);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        activeFlagListeners.clear();
    }

    @Override
    public void updateFriendCircleInfoView(PageEntity pageEntity, final List<FriendCircleInfoEntity> friendCircleEntities) {
        isloadingMore = false;
        isRefresh = false;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                MineCircleInfoFragment.this.friendCircleEntities.clear();
                MineCircleInfoFragment.this.friendCircleEntities.addAll(friendCircleEntities);
                view_mine_info_refresh.setRefreshing(false);
                friendCircleAdapter.hideFooterView();
                friendCircleAdapter.updateDatas(friendCircleEntities);
            }
        });
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        isloadingMore = false;
    }
}
